define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        user_models = require('js/apps/console/models'),
        utils = require('js/utils/tools'),
        tz = require('js/utils/tz'),
        cookie = require('js/utils/cookie'),
        app = Backbone.history;
    require('datetimepicker');
    require('multiselect');
    require('magnific');
    require('jquery-ui');

    var AddCoinListView = Backbone.View.extend({
        events: {
            'click #search': 'doSearch',
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.AddCoinCollection();
            this.user_collection = new user_models.UserCollection();
            this.checkedIds = [];
            this.collection.bind('change remove reset', this.renderWithData, this);
            this.uuid = "";
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        _getSearchOption: function () {
            var options = {};
            var searched = utils.getAllInput('#sidebar_right');
            options.enable_withdraw = searched.enable_withdraw;
            if (searched.id) {
                options.id = searched.id;
            }
            if (searched.operator != 0) {
                options.operator = searched.operator;
            }
            if (searched.user_id) {
                options.user_id = searched.user_id;
            }
            if (searched.created_at) {
                options.created_at = searched.created_at;
            }
            utils.saveSearched('op/add_coin', searched);
            return options;
        },
        doSearch: function () {
            this.doRefresh(true);
        },
        doRefresh: function (useSearch) {
            var options = {};
            if (useSearch) {
                options = this._getSearchOption();
            }
            options.$page = 1;
            options.$size = 300;
            options.$orderby = "-created_at";
            options._ = new Date().getTime();
            app.navigate(utils.composeQueryString('#op/add_coin/', options), {
                trigger: true
            });
        },
        confirmAddNewItem: function () {
            var awardInfo = $('#awardInfo').val();
            var noteInfo = $('#note').val();
            var statusInfo = $('#inputStatus').val();
            var that = this;
            if (awardInfo === undefined || awardInfo === "") {
                alert("请输入正确的上分信息");
                return;
            }
            var enable_withdraw = $('#enable_withdraw').val();
            var awardItems = awardInfo.split('\n');
            var postInfo = '{"detail_info":[';
            var confirm_message = '';
            for (var i = 0; i < awardItems.length; ++i) {
                var item = awardItems[i];
                var info = item.replace(/，/g, ",");
                info = info.split(",");
                if (info.length !== 3) {
                    alert("第" + (i + 1) + "行输入错误：" + info);
                    return;
                }
                postInfo += '{"user_name":"' + info[0] + '","user_id":"' + info[1] + '","amount":' + info[2] + '},';
                confirm_message += '用户名: ' + info[0] + ', user_id: ' + info[1] + ', 金额:' + info[2] + '\n'
            }

            postInfo = postInfo.substr(0, postInfo.length - 1);
            if("no_enter" != statusInfo){
                postInfo += '],"note":"' + noteInfo + '","black_type":"'+statusInfo + '"';
            }else{
                postInfo += '],"note":"' + noteInfo + '"';
            }
            if(enable_withdraw != 0){
                postInfo += ',"enable_withdraw":1}';
            }else{
                postInfo += '}';
            }
            if(window.confirm('谨慎操作，请再次确认:\n' + confirm_message)) {
                $.ajax({
                    url: '/admin/system_recharge/create/' + this.uuid,
                    type: 'POST',
                    headers: {
                        'X-AUTH-USER': cookie.getCookie('bigbang_user_id'),
                        'X-AUTH-TOKEN': cookie.getCookie('bigbang_user_token'),
                        'content-type': 'application/json'
                    },
                    data: postInfo,
                }).done(function (resp) {
                    notify.success('提示', '添加成功！');
                    $.magnificPopup.close();
                    that.doRefresh(false);
                }).fail(function (resp) {
                    notify.notifyResp(resp);
                });
            }
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/add_coin')
            }));

            var that = this;

            $('#addNewItem').magnificPopup({
                items: {
                    src: '#addNewItemPanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {
                        that.uuid = utils.generateUUID();
                        $('#cancelAddNewItem').off('click').click(function () {
                            $.magnificPopup.close();
                        });

                        $('#confirmAddNewItem').off('click').click(function () {
                            that.confirmAddNewItem();
                        });
                    }
                }
            });
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/add_coin/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('.datetime-input').datetimepicker({
                format: 'YYYY-MM-DD HH:mm:ss',
            });
            $('.date-input').datetimepicker({
                format: 'YYYY-MM-DD',
            });
            utils.getPaginator(that.options, this.collection.total, '#op/add_coin/');

            return this;
        },
        load: function () {
            
            var that = this;
            this.user_collection.fetch({
                reset: true,
                data: {'disable_paginate': 1},
                success: function () {
                    that.collection.fetch({
                        reset: true,
                        data: that.options,
                        error: function (c, r, o) {
                            notify.notifyResp(r);
                            $('#content').append('<h4 class="text-muted">无数据</h4>');
                        },
                    });
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                }
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/AddCoin.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            this.options.$size = 300;
            var view = new AddCoinListView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();
            return this;
        }
    });

});
